<template>
	<view class="me-container">
		<!-- 侧边栏（可展开/收起，简化为抽屉） -->
		<u-popup v-model="showSidebar" mode="left" width="520rpx">
			<view class="sidebar">
				<view class="sidebar-title">功能菜单</view>
				<u-cell-group>
					<u-cell-item icon="file-text" title="用户协议" @click="navigateToAgreement" />
					<u-cell-item icon="file-text" title="隐私政策" @click="navigateToPrivacy" />
				</u-cell-group>
				<u-button type="default" shape="circle" @click="showSidebar = false">收起</u-button>
			</view>
		</u-popup>
		<!-- 轮播图作为背景 -->
		<view class="banner-container">
			<swiper class="banner-swiper" circular :indicator-dots="false" :autoplay="true" interval="3000"
				duration="1000">
				<swiper-item v-for="(bannerItem, index) in userInfo.images" :key="index">
					<view class="banner-item">
						<image :src="globalConfig.site_url + bannerItem" mode="aspectFill" class="swiper-img"
							@error="handleImageError"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<view class="top-bar" :style="topBarStyle">
			<view class="avatar-box">
				<u-avatar size="large" :src="globalConfig.site_url + userInfo.image || '/static/avatar.png'" />
			</view>
			<view class="user-info">
				<view class="nickname">{{ userInfo.nickname || '未设置昵称' }}</view>
				<view class="desc">{{ userInfo.gender === '1' ? '男' : userInfo.gender === '2' ? '女' : '未知' }} ·
					{{ userInfo.signature || '未设置签名' }}
				</view>
				<u-button type="primary" size="mini" shape="circle" @click="navigateToEditPage">编辑</u-button>
			</view>
			<u-icon name="more-dot-fill" size="28" color="#fff" class="more-btn" @click="showSidebar = true" />
		</view>
		<!-- 数据卡片区 -->
		<view class="stats-section" v-if="globalConfig.examine != 1">
			<view class="stat-item" v-for="item in stats" :key="item.text">
				<text class="num">{{ item.num }}</text>
				<text class="label">{{ item.text }}</text>
			</view>
		</view>
		<!-- 动态模块 -->
		<view class="dynamic-section" v-if="globalConfig.examine != 1">
			<view class="dynamic-title">动态</view>
			<image class="panda" src="/static/panda-box.png" mode="aspectFit" v-if="posts.length === 0" />
			<view class="dynamic-empty" v-if="posts.length === 0">这个搭子有点懒 还没有发过动态</view>
			<view v-else>
				<view v-for="item in posts" :key="item.id" class="dynamic-card">
					<view class="card-header" @click="goDetail(item)">
						<!-- <u-avatar :src="item.user_info.image || ''" size="40" /> -->
						<view class="user-info">
							<!-- <text class="nickname">{{ item.user_info.nickname }}</text> -->
							<text class="time">{{ formatTime(item.createtime) }}</text>
						</view>
					</view>
					<view class="card-content" @click="goDetail(item)">{{ item.info }}</view>
					<view v-if="item.images && item.images.length" class="card-images" @click="goDetail(item)">
						<image v-for="(img, idx) in item.imageList" :key="idx" :src="globalConfig.site_url + img"
							mode="aspectFill" class="card-img" />
					</view>
					<view class="card-footer">
						<text class="location">{{ item.area_name }}</text>
						<!-- <view class="actions">
              <u-icon name="thumb-up" size="24" :color="item.liked ? '#ff4d4f' : '#8e24aa'"
                @click.stop="handleLike(item)" />
              <text>{{ item.likes_count }}</text>
              <u-icon name="chat" size="24" color="#8e24aa" style="margin-left: 24rpx;" @click="goDetail(item)" />
              <text>{{ item.comments_count }}</text>
            </view> -->
					</view>
				</view>
				<view v-if="loading" class="loading-text">加载中...</view>
				<view v-if="finished && posts.length > 0" class="finished-text">没有更多了</view>
			</view>
		</view>
		<!-- uView登录弹窗 (from shop-list.vue) -->
		<u-popup v-model="showLoginPopup" mode="center" border-radius="16" width="600rpx" :mask-close-able="true"
			@close="closeLoginPopup">
			<view class="login-popup">
				<view class="popup-header">
					<view class="popup-title">登录</view>
					<view class="popup-close" @click="closeLoginPopup">
						<u-icon name="close" color="#999" size="20"></u-icon>
					</view>
				</view>

				<view class="login-methods">
					<u-button type="success" shape="round" :loading="wechatLoading" @click="handleWechatLogin"
						:custom-style="{ backgroundColor: '#07c160', borderColor: '#07c160', marginBottom: '20rpx' }">
						<u-icon name="weixin-fill" color="#fff" size="20" style="margin-right: 10rpx"></u-icon>
						{{ wechatLoading ? '登录中...' : '微信登录' }}
					</u-button>
				</view>

				<view class="login-tips">
					<u-checkbox v-model="agreePolicy" shape="circle" active-color="#007aff" :size="32"
						style="margin-right: 10rpx;" />
					<text class="tips-text">我已阅读并同意</text>
					<text class="link-text" @click="showPrivacy('agreement')">《用户协议》</text>
					<text class="tips-text">和</text>
					<text class="link-text" @click="showPrivacy('policy')">《隐私政策》</text>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getUserInfo,
		getUserDynamic
	} from '@/api/user.js';
	import {
		mapGetters,
		mapActions,
		mapState
	} from 'vuex';
	import {
		checkLoginStatus,
		wechatMiniLogin
	} from '@/common/auth.js';
	export default {
		name: 'MeIndex',
		data() {
			return {
				showLoginPopup: false,
				agreePolicy: false,
				wechatLoading: false,
				showSidebar: false,
				userInfo: {},
				stats: [{
						text: '我关注',
						num: 0
					},
					{
						text: '访客',
						num: 0
					},
					{
						text: '粉丝',
						num: 0
					}
				],
				posts: [],
				page: 1,
				pageSize: 10,
				loading: false,
				finished: false,
				total: 0
			}
		},
		computed: {
			...mapState({
				globalConfig: state => state.config,
				userLocation: state => state.location,
			}),
			topBarStyle() {
				if (this.userInfo.images) {
					return {
						'background-image': `url(${this.userInfo.images})`,
						'background-size': 'cover',
						'background-position': 'center',
						'background-repeat': 'no-repeat'
					};
				}
				return {
					'background': '#2d2d2d'
				};
			}
		},
		onShow() {
			this.fetchUserData();
			this.fetchPosts(true);
			uni.$on('refreshMeIndex', () => {
				this.fetchUserData();
				this.fetchPosts(true);
			});
		},
		onUnload() {
			uni.$off('refreshMeIndex');
		},
		mounted() {
			this.fetchUserData();
			this.fetchPosts(true);
		},
		methods: {
			showPrivacy(type) {
				// 获取协议标题
				let title = type === 'agreement' ? '用户协议' : '隐私政策';
				// 获取全局配置里的 yinsi 内容
				const yinsi = this.globalConfig?.yinsi || '';
				uni.navigateTo({
					url: `/pages/common/rich-text?title=${encodeURIComponent(title)}&content=${encodeURIComponent(yinsi)}`
				});
			},
			formatTime(ts) {
				if (!ts) return '';
				const date = new Date(ts * 1000);
				const y = date.getFullYear();
				const m = (date.getMonth() + 1).toString().padStart(2, '0');
				const d = date.getDate().toString().padStart(2, '0');
				const h = date.getHours().toString().padStart(2, '0');
				const min = date.getMinutes().toString().padStart(2, '0');
				return `${y}-${m}-${d} ${h}:${min}`;
			},
			async navigateToEditPage() {
				const isLoggedIn = await checkLoginStatus();
				if (!isLoggedIn) {
					this.showLoginPopup = true;
					return;
				}
				uni.navigateTo({
					url: '/pages/me/edit'
				});
			},
			async fetchUserData() {
				try {
					// 添加时间戳参数防止缓存
					const userInfoRes = await getUserInfo({
						t: new Date().getTime()
					});
					if (userInfoRes.code == 1) {
						this.userInfo = userInfoRes.data || {};
						if (userInfoRes.stats) {
							this.stats = [{
									text: '我关注',
									num: userInfoRes.data.follower_count || 0
								},
								{
									text: '访客',
									num: userInfoRes.data.visitors_count || 0
								},
								{
									text: '粉丝',
									num: userInfoRes.data.follower_user_count || 0
								}
							];
						}
					} else {
						uni.showToast({
							title: '获取用户信息失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取用户数据失败',
						icon: 'none'
					});
				}
			},
			async fetchPosts(reset = false) {
				if (this.loading || this.finished) return;
				this.loading = true;
				if (reset) {
					this.page = 1;
					this.posts = [];
					this.finished = false;
				}
				try {
					const res = await getUserDynamic({
						page: this.page
					});
					console.log('user dynamic res:', res);
					if (res && res.data.code === 1) {
						const list = res.data.data.data.map(item => ({
							...item,
							showTime: this.formatTime(item.createtime),
							imageList: item.images ?
								item.images.split(',').filter(i => i) : []
						}));
						console.log(list, 'list');
						if (list.length < (res.data.per_page || this.pageSize)) this.finished = true;
						this.posts = this.posts.concat(list);
						this.page += 1;
						this.total = res.data.total || 0;
					} else {
						this.finished = true;
					}
				} catch (e) {
					uni.showToast({
						title: '动态加载失败',
						icon: 'none'
					});
				}
				this.loading = false;
			},
			onReachBottom() {
				this.fetchPosts();
			},
			goDetail(item) {
				console.log(item, 'goDetail');
				uni.navigateTo({
					url: `/pages/dynamic/comment?id=${item.id}`
				})
			},
			async handleWechatLogin() {
				// 判断有没有勾选隐私
				if (!this.agreePolicy) {
					this.$u.toast('请先勾选同意《用户协议》和《隐私政策》');
					return;
				}
				if (this.wechatLoading) return;
				this.wechatLoading = true;
				try {
					const result = await wechatMiniLogin();
					if (result.success) {
						this.$store.dispatch('fetchUserInfoAction');
						this.closeLoginPopup();
						this.$u.toast('登录成功');
						this.fetchUserData();
						this.fetchPosts(true);
					} else {
						throw new Error(result.message || '登录失败');
					}
				} catch (error) {
					this.$u.toast(error.message || '登录操作失败');
				} finally {
					this.wechatLoading = false;
				}
			},
			closeLoginPopup() {
				this.showLoginPopup = false;
				this.wechatLoading = false;
			},
		},
	}
</script>

<style scoped lang="less">
	.me-container {
		// padding-top: 100rpx;
		min-height: 100vh;
		background: #1a1a1a;
		color: #fff;
	}

	.top-bar {
		display: flex;
		align-items: center;
		padding: 32rpx;
		position: relative;
	}

	.avatar-box {
		margin-right: 24rpx;
	}

	.user-info {
		flex: 1;
	}

	.nickname {
		font-size: 36rpx;
		font-weight: bold;
		display: flex;
		align-items: center;
		gap: 12rpx;
		color: #fff;
	}

	.desc {
		color: #fff;
		font-size: 28rpx;
		margin-bottom: 8rpx;
		text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.5);
	}

	.more-btn {
		margin-left: 16rpx;
		color: #fff;
	}

	.stats-section {
		display: flex;
		justify-content: space-around;
		margin: 32rpx 0;
		background: #2d2d2d;
		padding: 20rpx 0;
		border-radius: 16rpx;
	}

	.stat-item {
		text-align: center;
	}

	.num {
		display: block;
		font-size: 32rpx;
		color: #fff;
		font-weight: bold;
	}

	.label {
		font-size: 24rpx;
		color: #ccc;
	}

	.dynamic-section {
		background: #1a1a1a;
		border-radius: 16rpx;
		margin: 0 32rpx 32rpx;
		padding: 0;
		text-align: center;
		position: relative;
		overflow: scroll;
		height: calc(100vh - 600rpx);
	}

	.dynamic-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #fff;
		padding: 24rpx 32rpx;
		text-align: left;
		border-bottom: 1rpx solid #333;
	}

	.panda {
		width: 120rpx;
		height: 120rpx;
		margin-bottom: 16rpx;
	}

	.dynamic-empty {
		color: #666;
		font-size: 28rpx;
		margin-bottom: 16rpx;
	}

	.my-room-btn {
		position: absolute;
		right: 32rpx;
		top: 32rpx;
	}

	.sidebar {
		padding: 32rpx;
		background: #2d2d2d;
		color: #fff;
	}

	.sidebar-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 24rpx;
		color: #fff;
	}

	.my-post-item {
		background: #23232b;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		padding: 24rpx;
		color: #fff;
		text-align: left;
	}

	.post-title {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 8rpx;
	}

	.post-content {
		font-size: 26rpx;
		color: #ccc;
		margin-bottom: 8rpx;
	}

	.post-time {
		font-size: 22rpx;
		color: #888;
		text-align: right;
	}

	.loading-text,
	.finished-text {
		color: #666;
		font-size: 26rpx;
		text-align: center;
		margin: 32rpx 0;
	}



	.dynamic-card {
		background: #2d2d2d;
		border-radius: 24rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.4);
		margin: 0 32rpx 24rpx;
		padding: 32rpx;
		transition: box-shadow 0.2s;

		.card-header {
			display: flex;
			align-items: center;
			margin-bottom: 16rpx;
		}

		.user-info {
			display: flex;
			flex-direction: column;
			margin-left: 16rpx;
		}

		.nickname {
			font-size: 28rpx;
			font-weight: bold;
			color: #23243a;
		}

		.time {
			font-size: 22rpx;
			color: #b0b0b0;
			margin-top: 4rpx;
			text-align: left;
		}

		.card-content {
			font-size: 28rpx;
			color: #fff;
			margin-bottom: 16rpx;
			text-align: left;
		}

		.card-images {
			display: flex;
			gap: 12rpx;
			margin-bottom: 16rpx;
		}

		.card-img {
			width: 120rpx;
			height: 120rpx;
			border-radius: 12rpx;
			object-fit: cover;
		}

		.card-footer {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.location {
			font-size: 22rpx;
			color: #aaa;
		}

		.actions {
			display: flex;
			align-items: center;
			color: #8e24aa;
			font-size: 24rpx;
		}

		.fab-btn {
			position: fixed;
			right: 48rpx;
			bottom: 180rpx;
			z-index: 10;
		}
	}


	.banner-container {
		width: 100%;
		height: 280rpx;
		/* Use explicit height to fix rendering issue */
		z-index: 1;
		/* Removed all original styles like padding, bg-color */
	}

	.banner-swiper {
		width: 100%;
		height: 100%;
		border-radius: 0;
		/* Swiper is background, so no radius */
		overflow: hidden;
	}

	.banner-item {
		width: 100%;
		height: 100%;
	}

	.swiper-img {
		width: 100%;
		height: 100%;
		border-radius: 0;
		/* Image fills swiper, no radius */
	}

	.banner-placeholder {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #f5f6fa;
		border-radius: 0;
		color: #999;
		font-size: 28rpx;
	}
</style>